package it.saga.pes.frontoffice.servizi.struts2.upload.action;

import it.saga.pes.business.bean.infra.servizi.DocumentoBean;
import it.saga.pes.frontoffice.servizi.struts2.rsm2.action.ScolasticiMensaAction;
import it.saga.pes.frontoffice.servizi.struts2.upload.bean.Allegato;
import it.saga.pes.frontoffice.servizi.struts2.upload.bean.MsgUpload;
import it.saga.pes.infra.configuration.ConfigurationManager;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 
 	Azione generica per gli allegati , mette in sessione LISTA_ALLEGATI, da mettere nella pratica
 	
	Le dimensioni massime vanno specificate nelle proprietà struts
 	
 	fileUpload.maximumSize
	struts.multipart.maxSize 

 */

@SuppressWarnings({ "serial", "unchecked" })
public class UploadAction extends ActionSupport implements ServletRequestAware, SessionAware , Preparable{
	
	private static final Log log = LogFactory.getLog(ScolasticiMensaAction.class);
	
	private static String LISTA_ALLEGATI = "LISTA_ALLEGATI";
	private static String LISTA_TIPI_ALLEGATO = "LISTA_TIPI_ALLEGATO";
	
	private List<Allegato> allegati = null;
	private List<DocumentoBean> listaTipiAllegato;
	
	private File[] fileAllegato;
	private String[] fileAllegatoFileName;
	private String[] fileAllegatoContentType;
	
	private HttpServletRequest servletRequest;

	private String backAction;
	private String backNamespace;
	private String nextAction;
	private String nextNamespace;
	
	private int id ;
	
	public long codice ;
	
	private Map<String, Object> session;
	
	private InputStream stream;
	public InputStream getStream() {
	    return stream;
	  }
	
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public void prepare() throws Exception {
		allegati = (List<Allegato>) session.get(LISTA_ALLEGATI);
		System.out.println("Allegati:"+ToStringBuilder.reflectionToString(allegati));
		if (allegati == null)
			allegati = new ArrayList<Allegato>();
		session.put(LISTA_ALLEGATI, allegati);
		listaTipiAllegato =(List<DocumentoBean>) session.get(LISTA_TIPI_ALLEGATO);
		System.out.println("listaTipiAllegato:"+ToStringBuilder.reflectionToString(listaTipiAllegato));
		// MATCH tipo allegato richiesto con allegati presenti	
		for(DocumentoBean t: listaTipiAllegato ){
			t.setFilename("");
			for(Allegato a : allegati){
				if(t.getCodice().equals(a.getCodice())){
					t.setFilename(a.getOriginalFilename());
					break;
				}
			}
		}
		session.put(LISTA_TIPI_ALLEGATO, listaTipiAllegato);
	}
	
	@SkipValidation
	public String list() {
		return SUCCESS;
	}

	public String add() {
		allegati = (List<Allegato>) session.get(LISTA_ALLEGATI);
		String filePath = servletRequest.getSession().getServletContext().getRealPath("/repository");
		System.out.println("Server path:" + filePath);
		try {
			for (int i =0 ; fileAllegato!=null && i< fileAllegato.length;i++) {
				// TODO controllare esistenza
				if(fileAllegato[i]!=null){
					System.out.println("** "+fileAllegatoFileName[i]);
					File fileToCreate = new File(filePath, fileAllegatoFileName[i]);
					FileUtils.copyFile(fileAllegato[i], fileToCreate);
					Allegato a = new Allegato();
					a.setFilename(fileAllegatoFileName[i]);
					a.setUrl(fileToCreate.getPath());
					a.setTimestamp(new Date());
					allegati.add(a);
				}
			}
			session.put(LISTA_ALLEGATI, allegati);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}
	
	public String addAjax() {
		allegati = (List<Allegato>) session.get(LISTA_ALLEGATI);
		String documentPath = ConfigurationManager.CONF_SERVICE_PATH_DOCUMENT;
		System.out.println("document path:" + documentPath);
		System.out.println("codice:" + codice);
		MsgUpload msg = new MsgUpload();
		try {
			if(fileAllegato!=null ){
				for (int i =0 ; i< fileAllegato.length;i++) {
					// TODO controllare esistenza , se presente errore
					System.out.println("** "+fileAllegatoFileName[i]);
					if(fileAllegato[i]!=null){
						String guid = RandomStringUtils.randomAlphanumeric(10);
						//File fileToCreate = new File(documentPath, fileAllegatoFileName[i]);
						String filename = guid+"_"+fileAllegatoFileName[i].replaceAll(" ", "_");				
						File fileToCreate = new File(documentPath, filename);
						FileUtils.copyFile(fileAllegato[i], fileToCreate);
						Allegato a = new Allegato();
						a.setOriginalFilename(fileAllegatoFileName[i]);
						a.setUrl(fileToCreate.getPath());
						a.setTimestamp(new Date());
						a.setFilename(filename);
						a.setCodice(codice);
						allegati.add(a);
						msg.setStatus("SUCCESS");
						msg.setOriginalFilename(fileAllegatoFileName[i]);
						msg.setFilename(filename);
					}else{
						msg.setStatus("ERROR");
						msg.setError("Errore caricamento file");
					}
				}
			}else{
				msg.setStatus("ERROR");
				msg.setError("Errore caricamento file");
			}
			session.put(LISTA_ALLEGATI, allegati);
		} catch (Exception e) {
			msg.setStatus("ERROR");
			msg.setError(e.toString());
		}
		Gson gson = new GsonBuilder().create();
		String str = gson.toJson(msg);
	    stream = new ByteArrayInputStream(str.getBytes());
		return SUCCESS;
	}
	
	public String removeAjax() {
		MsgUpload msg = new MsgUpload();
		try {
			String documentPath = ConfigurationManager.CONF_SERVICE_PATH_DOCUMENT;
			Allegato a = allegati.get(id);
			System.out.println("Allegato da cancellare:"+a);
			File file = new File(documentPath,a.getFilename());
			boolean res = file.delete();
			if(res==false){
				msg.setStatus("ERROR");
				msg.setError("Errore cancellazione file");
			}else{
				allegati.remove(id);
				session.put(LISTA_ALLEGATI, allegati);
				msg.setStatus("SUCCESS");
			}
		} catch (Exception e) {
			msg.setStatus("ERROR");
			msg.setError("Errore cancellazione file");
		}
		Gson gson = new GsonBuilder().create();
		String str = gson.toJson(msg);
	    stream = new ByteArrayInputStream(str.getBytes());
		return SUCCESS;
	}
	
	public String remove() {
		try {
			// recuperare confifurazione
			//String filePath = servletRequest.getSession().getServletContext().getRealPath("/repository");
			String documentPath = ConfigurationManager.CONF_SERVICE_PATH_DOCUMENT;
			Allegato a = allegati.get(id);
			System.out.println("Allegato:"+a);
			File file = new File(documentPath,a.getFilename());
			boolean res = file.delete();
			if(res==false){
				log.error("File :"+file.getName()+" non cancellato");
				// set error validation
				return INPUT;
			}
			allegati.remove(id);
			session.put(LISTA_ALLEGATI, allegati);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}
	
	
	
	public String next() {
		return "next";
	}

	public String back() {
		return "back";
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}

	public List<Allegato> getAllegati() {
		return allegati;
	}

	public void setAllegati(List<Allegato> allegati) {
		this.allegati = allegati;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getBackAction() {
		return backAction;
	}

	public void setBackAction(String backAction) {
		this.backAction = backAction;
	}

	public String getBackNamespace() {
		return backNamespace;
	}

	public void setBackNamespace(String backNamespace) {
		this.backNamespace = backNamespace;
	}

	public String getNextAction() {
		return nextAction;
	}

	public void setNextAction(String nextAction) {
		this.nextAction = nextAction;
	}

	public String getNextNamespace() {
		return nextNamespace;
	}

	public void setNextNamespace(String nextNamespace) {
		this.nextNamespace = nextNamespace;
	}

	public List<DocumentoBean> getListaTipiAllegato() {
		return listaTipiAllegato;
	}

	public void setListaTipiAllegato(List<DocumentoBean> listaTipiAllegato) {
		this.listaTipiAllegato = listaTipiAllegato;
	}

	public File[] getFileAllegato() {
		return fileAllegato;
	}

	public void setFileAllegato(File[] fileAllegato) {
		this.fileAllegato = fileAllegato;
	}

	public String[] getFileAllegatoFileName() {
		return fileAllegatoFileName;
	}

	public void setFileAllegatoFileName(String[] fileAllegatoFileName) {
		this.fileAllegatoFileName = fileAllegatoFileName;
	}

	public String[] getFileAllegatoContentType() {
		return fileAllegatoContentType;
	}

	public void setFileAllegatoContentType(String[] fileAllegatoContentType) {
		this.fileAllegatoContentType = fileAllegatoContentType;
	}

}
